/**
 * 
 */
package com.cqan.digital.controller;

import static com.cqan.common.ViewName.DIGITAL_EDIT;
import static com.cqan.common.ViewName.DIGITAL_LIST;

import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.cqan.controller.BaseController;
import com.cqan.digital.entity.Digital;
import com.cqan.digital.service.DigitalService;
import com.cqan.exception.AppException;
import com.cqan.orm.PropertyFilter;
import com.cqan.orm.PropertyFilter.MatchType;
import com.cqan.product.entity.Product;
import com.cqan.product.service.ProductService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * @Description 数据控制器
 * @author slaton.wu@gmail.com
 * @date 2012-7-5下午5:23:51
 *
 */
@Controller
@RequestMapping("/digital")
public class DigitalController extends BaseController<Digital> {
	
	@Resource(name="digitalService")
	private DigitalService digitalService;
	
	@Resource(name="productService")
	private ProductService productService;
	
	@RequestMapping(value="/list.htm")
	public ModelAndView list(Integer pageNo,Long pid,HttpServletRequest request)throws AppException{
		ModelAndView mav = new ModelAndView(DIGITAL_LIST);
		if (pid==null) {
			pid=0l;
		}
		PropertyFilter filter = new PropertyFilter("EQL_pid", String.valueOf(pid));
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		filters.add(filter);
		page.setPageNo(pageNo);
		List<PropertyFilter> pfs = Lists.newArrayList();
		pfs.add(new PropertyFilter("EQB_status", "1"));
		List<Product> pts = productService.getList(pfs);
		page = digitalService.search(page, filters);
		mav.addObject("pts", pts);
		mav.addObject("pid", pid);
		mav.addObject("page", page);
		return mav;
	}
	
	@RequestMapping(value="/save.htm")
	public ModelAndView save(Long id,HttpServletRequest request)throws AppException{
		ModelAndView mav =null;
		try {
			Digital digital = this.getRequestEntity(request);
			if(id!=null){
				Digital d = this.digitalService.get(id);
				this.copyProperties(d, digital);
				this.digitalService.update(d);
				mav = new ModelAndView(new RedirectView("list.htm?pid="+digital.getPid()));
				return mav;
			}
			digital.setCreateTime(Calendar.getInstance().getTime());
			this.digitalService.add(digital);
			mav = new ModelAndView(new RedirectView("list.htm?pid="+digital.getPid()));
			
		} catch (Exception e) {
			e.printStackTrace();
			 mav = new ModelAndView(DIGITAL_LIST);
			throw new AppException();
		}	
		return mav;
	}
	
	@RequestMapping(value="/edit.htm",method=RequestMethod.GET)
	public ModelAndView edit(Long id,Long productId,Long pid)throws AppException{
		ModelAndView mav = new ModelAndView(DIGITAL_EDIT);
		 List<Product> products = productService.findBy("status",true, MatchType.EQ);
		 Digital digital = null;
		 if (id!=null) {
			 digital = digitalService.get(id);
		}else{
			digital = new Digital();
			digital.setPid(pid);
		}
		mav.addObject("digital", digital);
		mav.addObject("products", products);
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value="/delete.htm",method=RequestMethod.POST)
	public String delete(String ids)throws AppException{
		try {
			if (ids!=null) {
				StringTokenizer st = new StringTokenizer(ids,"-");
				List<Long> list = Lists.newArrayList();
				while (st.hasMoreTokens()) {
					String id = st.nextToken();
					if (id!=null&&!"".equals(id)) {
						list.add(Long.parseLong(id));
					}
				}
				digitalService.delete(list);
				return "删除成功！";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return  "现在还不能删除此节点！";
		}
		return  "删除失败！";
	}
	
	
	/**
	 * 对数据节点进行 粘贴，复制，剪切操作
	 * @param pid 当前节点父节点
	 * @param ids 操作节点id如1-2-3-4-5
	 * @param type 类型：复制:copy 粘贴:paste 剪切:cut
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/operate.htm")
	public String operate(Long pid,String ids,String type,HttpServletRequest request){
		try {
			if(type.equals("copy")||type.equals("cut")){
				copy(pid, dealIds(ids), request,type);
				return "操作成功！";
			}
			if(type.equals("paste")){
				
				return paste(pid, request);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "操作成功";
		}
		return "异常的操作！";
	}
	
	//复制
	private void copy(Long pid,List<Long> ids,HttpServletRequest request,String type){
		Map<String,Object> data = Maps.newHashMap();
		data.put("ids", ids);
		data.put("type",type);
		request.getSession().setAttribute("operate", data);
		
	}
	
	@SuppressWarnings("unchecked")
	private String paste(Long pid,HttpServletRequest request) throws Exception{
		
		Map<String,Object> data =(Map<String, Object>) request.getSession().getAttribute("operate");
		if (data==null) {
			return "无数据可粘贴！";
		}
		List<Long> ids = (List<Long>) data.get("ids");
		String  type = (String) data.get("type");
		if (ids==null||ids.size()==0) {
			return "无数据可粘贴！";
		}
		List<Digital> digitals = digitalService.get(ids);
		if (digitals!=null&&digitals.size()>0) {
			for (Digital d : digitals) {
				Digital digital = new Digital();
				BeanUtils.copyProperties(digital,d);
				digital.setPid(pid);
				digital.setId(null);
				digital.setCreateTime(Calendar.getInstance().getTime());
				digitalService.add(digital);
			}
			if (type.equals("cut")) {
				digitalService.delete(ids);
			}
		}
		request.getSession().removeAttribute("operate");
		return "粘贴成功！";
		
	}
	
	private List<Long> dealIds(String ids){
		List<Long> data = Lists.newArrayList();
		if (ids!=null&&ids.length()>0) {
			StringTokenizer st = new StringTokenizer(ids, "-");
			while (st.hasMoreTokens()) {
				String id =  st.nextToken();
				if (id!=null&&!"".equals(id)) {
					data.add(Long.parseLong(id));
				}
				
			}
		}
		return data;
	}
	
	
}
